package com.crm.controller;

import java.io.IOException;
import java.sql.Time;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.crm.model.pojo.Complaint;
import com.crm.model.pojo.Customer;
import com.crm.model.pojo.Dictionary;
import com.crm.services.ComplaintServices;
import com.crm.services.ContactServices;
import com.crm.services.CustomerServices;
import com.crm.services.DictionaryServices;
import com.crm.services.QAServices;
import com.crm.services.UserServices;
import com.crm.util.LoginUtil;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("/aftersale")
public class ComplaintController {
	@Autowired
	ComplaintServices complaintServices;
	@Autowired
	UserServices userservices;
	@Autowired
	CustomerServices customerServices;
	@Autowired
	DictionaryServices dictionaryServices;
	@Autowired
	ContactServices contactServices;
	@Autowired
	QAServices qaServices;
	
	/**
	 * 查询客户投诉
	 * 
	 * @return
	 */
	@GetMapping("/complaint")
	public ModelAndView findcomplain(Integer pageNum, Integer pageSize,Integer statueID,String search) {
		if (pageNum == null)
			pageNum = 1;
		if (pageSize == null)
			pageSize = 6;
		ModelAndView mv = new ModelAndView("/aftersale/complaint");
		System.out.println("投诉！");
		// 查询分页客户投诉
		List<Map<String, String>> selectPage = complaintServices.selectPage(pageNum, pageSize, statueID, search);
		System.out.println(selectPage);
		String jsonString = JSONObject.toJSONString(selectPage);
		System.out.println(jsonString);
		// 获取分页信息
		PageInfo<Map<String, String>> page = new PageInfo<Map<String, String>>(selectPage);
		String pageInfo = JSONObject.toJSONString(page);
		System.out.println(page);
		mv.addObject("list", jsonString);
		mv.addObject("page", page);
		mv.addObject("pageinfo", pageInfo);
		return mv;
	}

	/**
	 * 分页查询获取投诉（刷新表单）
	 * @param pageNum
	 * @param pageSize
	 * @param statueID
	 * @param search
	 * @return
	 */
	@PostMapping("/complaint")
	@ResponseBody	
	public PageInfo<Map<String, String>> findcomplainNew(Integer pageNum, Integer pageSize,Integer statueID,String search) {
		if (pageNum == null)
			pageNum = 1;
		if (pageSize == null)
			pageSize = 6;
		//分页查询投诉
		System.out.println("Complaint:"+pageNum+"\t"+pageSize+"\t"+statueID+"\t"+search);
		List<Map<String, String>> selectPage = complaintServices.selectPage(pageNum, pageSize, statueID, search);
		//获取分页信息
		PageInfo<Map<String, String>> page = new PageInfo<Map<String, String>>(selectPage);
		return page;
	}
	
	/**
	 * 查询qa用于投诉
	 */
	@RequestMapping("/selectAllQAToComplaint")
	@ResponseBody
	public JSONObject selectAllQA() {
		// 查询投诉解决办法（从qa表）
		List<Map<String, String>> handleComplaint = qaServices.handleComplaint();
		System.out.println("查询qa:"+handleComplaint);	
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("handleComplaint", handleComplaint);
		return jsonObject;
	}
	
	/**
	 * 查询单条
	 * 
	 * @param complaintid
	 * @param model
	 * @return
	 */
	@PostMapping("/complaintOne")
	@ResponseBody
	public JSONObject getComplaintByCid(@RequestParam("c_id") Integer complaintid) {
		// 查询所有客户
		List<Map<String, String>> allCustomerName = customerServices.selectAllCustomer();
		System.out.println("客户名：" + allCustomerName);
		// 查询所有用户名
		List<Map<String, String>> allusername = userservices.selectUserAll();
		System.out.println("所有用户:" + allusername);
		// 查询投诉分类
		List<Map<String, String>> selectComplainttype = complaintServices.selectComplainttype(1399);
		System.out.println("投诉分类：" + selectComplainttype);
		// 查询花费时间
		List<Dictionary> spendTime = dictionaryServices.findByDictParentid(1412);
		System.out.println("花费时间：" + spendTime);
		
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("comclassify", selectComplainttype);
		jsonObject.put("firstman", allusername);
		jsonObject.put("comcustid", allCustomerName);
		jsonObject.put("comspendtime", spendTime);
		System.out.println("投诉编号：" + complaintid);
		//id查询单条投诉信息
		Map<String, String> complaint = complaintServices.selectByCid(complaintid);
		jsonObject.put("allcomplaint", complaint);
		//根据编号查询投诉人
		Complaint findByid = complaintServices.findByid(complaintid);
		System.out.println(findByid.getConId());
		List<Map<String, String>> selectcustTocon = contactServices.selectcustTocon(findByid.getConId());
		System.out.println("投诉人:"+selectcustTocon);
		jsonObject.put("comcustmanid", selectcustTocon);// 投诉人
		return jsonObject;
	}

	/**
	 * id逻辑删除
	 * 
	 * @param complaintId
	 * @return
	 */
	@RequestMapping("/deleteoneComplaint")
	@ResponseBody
	public JSONObject deleteone(@RequestParam("ID") Integer complaintId) {
		JSONObject jsonObject = new JSONObject();
		Map<String, String> selectByCid = complaintServices.selectByCid(complaintId);
		String resultID = String.valueOf(selectByCid.get("comresult"));
		if (resultID.equals("1411")) {
			complaintServices.deleteByStatue(complaintId);
		} else if (resultID==null || resultID=="" || "null".equals(resultID)) {
			complaintServices.deleteByStatue(complaintId);
		}else {
			jsonObject.put("resultID", resultID);
		}
		return jsonObject;
	}

	/**
	 * 根据客户编号查询联系人
	 * 
	 * @param conName
	 */
	@RequestMapping("/custTocon")
	@ResponseBody
	public JSONObject selectcusttocon(@RequestParam("custid") Integer custid) {
		List<Map<String, String>> selectcustTocon = contactServices.selectcustTocon(custid);
		JSONObject jsonObject = new JSONObject();
		System.out.println("11111"+selectcustTocon);
		jsonObject.put("comcustmanid", selectcustTocon);// 投诉人
		return jsonObject;
	}

	/**
	 * 新增时查询对应可选数据
	 * @return
	 */
	@PostMapping("/chooseOptions")
	@ResponseBody
	public JSONObject addoptions() {
		// 查询所有客户
		List<Map<String, String>> allCustomerName = customerServices.selectAllCustomer();
		System.out.println("客户名：" + allCustomerName);
		// 查询所有用户名
		List<Map<String, String>> allusername = userservices.selectUserAll();
		System.out.println("所有用户:" + allusername);
		/*// 查询所有联系人
		List<Map<String, String>> selectAllBytype = contactServices.selectAllBytype();
		System.out.println("所有联系人:" + selectAllBytype);*/
		// 查询投诉分类
		List<Map<String, String>> selectComplainttype = complaintServices.selectComplainttype(1399);
		System.out.println("投诉分类：" + selectComplainttype);
		// 查询花费时间
		List<Dictionary> spendTime = dictionaryServices.findByDictParentid(1412);
		System.out.println("花费时间：" + spendTime);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("comclassify", selectComplainttype);
		jsonObject.put("allusername", allusername);
		jsonObject.put("comcustid", allCustomerName);
		jsonObject.put("comspendtime", spendTime);
		jsonObject.put("user", LoginUtil.getUser());
		return jsonObject;
	}

	/**
	 * 新增投诉
	 * @param comcustid
	 * @param comtheme
	 * @param firstman
	 * @param comclassify
	 * @param comdisc
	 * @param date1
	 * @param time1
	 * @param comcustmanid
	 * @param comurgency
	 * @param comprocess
	 * @param comrusult
	 * @param comspendtime
	 * @param comfeedbock
	 * @param comreturn
	 * @param comremark
	 * @return
	 */
	@PostMapping("/addcomplaint")
	@ResponseBody
	public String addcomplaint(@RequestParam(name = "comcustid", required = false) Integer comcustid,
			@RequestParam(name = "comtheme", required = false) String comtheme,
			@RequestParam(name = "firstman", required = false) Integer firstman,
			@RequestParam(name = "comclassify", required = false) Integer comclassify,
			@RequestParam(name = "comdisc", required = false) String comdisc,
			@RequestParam(name = "date1", required = false) String date1,
			@RequestParam(name = "time1", required = false) String time1,
			@RequestParam(name = "comcustmanid", required = false) Integer comcustmanid,
			@RequestParam(name = "comurgency", required = false) Integer comurgency,
			@RequestParam(name = "comprocess", required = false) String comprocess,
			@RequestParam(name = "comrusult", required = false) Integer comrusult,
			@RequestParam(name = "comspendtime", required = false) Integer comspendtime,
			@RequestParam(name = "comfeedbock", required = false) String comfeedbock,
			@RequestParam(name = "comreturn", required = false) String comreturn,
			@RequestParam(name = "comremark", required = false) String comremark) {
		// 转换日期格式
		java.sql.Date date = java.sql.Date.valueOf(date1.substring(0, 10));
		System.out.println(time1);
		Time time = java.sql.Time.valueOf(time1);
		System.out.println("客户：" + comcustid);
		System.out.println("主题" + comtheme);
		System.out.println("首问执行人：" + firstman);
		System.out.println("类型：" + comclassify);
		System.out.println("描述：" + comdisc);
		System.out.println("日期：" + date);
		System.out.println("时间：" + time);
		System.out.println("投诉人：" + comcustmanid);
		System.out.println("紧急程度：" + comurgency);
		System.out.println("处理过程：" + comprocess);
		System.out.println("处理结果：" + comrusult);
		System.out.println("花费时间：" + comspendtime);
		System.out.println("反馈：" + comfeedbock);
		System.out.println("回访：" + comreturn);
		System.out.println("备注：" + comremark);
		Complaint complaint = new Complaint();
		// 添加
		Customer findByCust = customerServices.findByCustIdPage(comcustid);
		complaint.setCustomer(findByCust);// 客户
		complaint.setCTheme(comtheme);// 主题
		complaint.setC_userID(firstman);// 首问执行人
		if (comclassify!=null) {
			complaint.setCClassifyid(comclassify);// 类型
		}else {
			complaint.setCClassifyid(1403);// 类型
		}
		complaint.setCDescription(comdisc);// 描述
		complaint.setCDate(date);// 日期
		complaint.setCTime(time);// 时间
		complaint.setConId(comcustmanid);// 投诉人
		if (comspendtime!=null) {
			complaint.setC_spentTimeId(comspendtime);// 花费时间
		}
		complaint.setCUrgency(comurgency);// 紧急程度
		complaint.setCProcess(comprocess);// 处理过程
		complaint.setCResult(comrusult);// 处理结果
		complaint.setCFeedback(comfeedbock);// 反馈
		complaint.setCReturn(comreturn);// 回访
		complaint.setCRemark(comremark);// 备注
		complaint.setStatue(1206);// 状态
		Complaint addComplaint = complaintServices.addComplaint(complaint);
		System.out.println("添加：" + addComplaint);
		return "添加！";
	}

	/**
	 * 编辑投诉
	 * 
	 * @param comcustid
	 * @return
	 */
	@PostMapping("/updatecomplaint")
	@ResponseBody
	public String updatecomplaint(@RequestParam("ID") Integer cid,
			@RequestParam(name = "comcustid", required = false) Integer comcustid,
			@RequestParam(name = "comtheme", required = false) String comtheme,
			@RequestParam(name = "firstman", required = false) Integer firstman,
			@RequestParam(name = "comclassify", required = false) Integer comclassify,
			@RequestParam(name = "comdisc", required = false) String comdisc,
			@RequestParam(name = "date1", required = false) String date1,
			@RequestParam(name = "time1", required = false) String time1,
			@RequestParam(name = "comcustmanid", required = false) Integer comcustmanid,
			@RequestParam(name = "comurgency", required = false) Integer comurgency,
			@RequestParam(name = "comprocess", required = false) String comprocess,
			@RequestParam(name = "comrusult", required = false) Integer comrusult,
			@RequestParam(name = "comspendtime", required = false) Integer comspendtime,
			@RequestParam(name = "comfeedbock", required = false) String comfeedbock,
			@RequestParam(name = "comreturn", required = false) String comreturn,
			@RequestParam(name = "comremark", required = false) String comremark) {
		// 转换日期格式
		java.sql.Date date = java.sql.Date.valueOf(date1.substring(0, 10));
		System.out.println(time1);
		Time time = java.sql.Time.valueOf(time1);
		Complaint complaint = new Complaint();
		// 修改
		Customer findByCust = customerServices.findByCustIdPage(comcustid);
		complaint.setCId(cid);
		complaint.setCustomer(findByCust);// 客户
		complaint.setCTheme(comtheme);// 主题
		complaint.setC_userID(firstman);// 首问执行人
		complaint.setCClassifyid(comclassify);// 类型
		complaint.setCDescription(comdisc);// 描述
		complaint.setCDate(date);// 日期
		complaint.setCTime(time);// 时间
		complaint.setConId(comcustmanid);// 投诉人
		complaint.setCUrgency(comurgency);// 紧急程度
		complaint.setCProcess(comprocess);// 处理过程
		complaint.setCResult(comrusult);// 处理结果
		complaint.setC_spentTimeId(comspendtime);// 花费时间
		complaint.setCFeedback(comfeedbock);// 反馈
		complaint.setCReturn(comreturn);// 回访
		complaint.setCRemark(comremark);// 备注
		complaint.setStatue(1206);// 状态
		Complaint addComplaint = complaintServices.addComplaint(complaint);
		System.out.println("更新：" + addComplaint);
		return "编辑！";
	}
	
	/**
	 * 导出
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "ComplaintExcelDownloads", method = RequestMethod.GET)
    public void downloadAllClassmate(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("投诉表");

        List<Map<String, String>> selectAll = complaintServices.selectAllInfo();
      
        String fileName = "complaintinfo"  + ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据

        int rowNum = 1;

        String[] headers = { "编号", "投诉主题","分类", "对应客户", "日期","时间","紧急程度","首问接待人","处理结果","投诉人","状态"};
        //headers表示excel表中第一行的表头

        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头

        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (Map<String, String> map : selectAll) {
        	HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(String.valueOf(map.get("ID")));
            row1.createCell(1).setCellValue(String.valueOf(map.get("comtheme")));
            row1.createCell(2).setCellValue(String.valueOf(map.get("comclassify")));
            row1.createCell(3).setCellValue(map.get("comcust"));
            row1.createCell(4).setCellValue(map.get("comdate"));
            row1.createCell(5).setCellValue(map.get("comtime"));
            row1.createCell(6).setCellValue(map.get("comurgency"));
            row1.createCell(7).setCellValue(map.get("comafterman"));
            row1.createCell(8).setCellValue(map.get("comresult"));
            row1.createCell(9).setCellValue(map.get("comman"));
            row1.createCell(10).setCellValue(map.get("statue"));
            rowNum++;
      		}
              
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

}
